<template>
  <div>
    <div class="fillRefundInfo">
      <div class="my-header">
        <i class="back iconfont icon-left" @click="$router.go(-1)"></i>
        <strong>填写售后信息</strong>
        <i style="min-width: 0.65rem;"></i>
      </div>
      <div class="refund-from">
        <div class="cell-from-item" @click="()=>stateVisible=true" v-if="returnGoods.orderStatus !== 2">
          <span class="title">货品情况 </span>
          <div class="content">
            <input class="input-select" type="text" readonly :value="returnDetails.returnGoodsStatus|formatStatus" placeholder="">
          </div>
          <i class="iconfont icon-right"></i>
        </div>
        <div class="cell-from-item" v-else>
          <span class="title">货品情况 </span>
          <div class="content">
            <input class="input-select gray" type="text" readonly :value="returnDetails.returnGoodsStatus=1|formatStatus" placeholder="">
          </div>
        </div>
        <div class="cell-from-item" @click="()=>reasonVisible=true">
          <span class="title">退款原因 </span>
          <div class="content">
            <input class="input-select" type="text" readonly :value="returnDetails.returnReason" placeholder="">
          </div>
          <i class="iconfont icon-right"></i>
        </div>
        <div class="cell-from-item">
          <span class="title">退款金额 </span>
          <div class="content">
            <span class="bgc">&yen;{{returnTotalMoney|formatMoney}}</span>
          </div>
        </div>
        <div class="cell-from-item">
          <span class="title">退款运费 </span>
          <div class="content">
            <input type="tel" v-bind:placeholder="freightPlaceholder" v-model="freight">
            <!--<span class="bgc">&yen;{{returnGoods.orderFreight|formatMoney}}</span>-->
          </div>
        </div>
      </div>
      <div class="explain">
        <textarea placeholder="请输入售后说明" rows="4" v-model="returnDetails.returnNote"></textarea>
      </div>
      <div class="upload">
        <h3>上传凭证</h3>
        <div>
          <div class="image-list">
            <div style="text-align:center" ref="divGenres" class="list-default-img" v-show="isPhoto" @click.stop="addPic">
              <img src="./../../assets/common/images/camera.png" />
              <br>
              <span>请选择或者拍照上传照片</span>
              <!-- accept="image/jpg,image/png,image/jpeg,image/gif"-->
              <input type="file" accept = 'image/*' @change="onFileChange" style="display: none;">
            </div>
            <ul class="list-ul" v-show="!isPhoto">
              <li class="list-li " v-for="(iu, index) in imgUrls" :key="index">
                <a class="list-link" @click='previewImage(iu)'>
                  <img :src="iu">
                </a>
                <span class="list-img-close" @click='delImage(index)'></span>
              </li>
              <li class="list-li" v-if="isAdd">
                <span class="add-img" @click.stop="addPic"> </span>
              </li>
            </ul>
          </div>
          <!--<button @click="saveImage">上传</button>-->
        </div>
      </div>
      <div class="submit">
        <button @click="submit()">提交售后申请</button>
      </div>
      <!--货品情况 退款原因-->
      <mt-popup v-model="stateVisible" position="bottom" class="refund-pricker">
        <mt-picker ref="statePickerDataPicker" :slots="stateSlots" valueKey="name" :showToolbar="true">
          <slot>
            <div class="picker-header">
              <span @click="()=>stateVisible=false">取消</span>
              <span class="red" @click="handlestatePickerDataConfirm()">确认</span>
            </div>
          </slot>
        </mt-picker>
      </mt-popup>
      <mt-popup v-model="reasonVisible" position="bottom" class="refund-pricker">
        <mt-picker ref="reasonPicker" :slots="reasonSlots" valueKey="name" :showToolbar="true">
          <slot>
            <div class="picker-header">
              <span @click="()=>reasonVisible=false">取消</span>
              <span class="red" @click="handleReasonConfirm()">确认</span>
            </div>
          </slot>
        </mt-picker>
      </mt-popup>
      <!--货品情况 退款原因-->
      <!--<awesome-picker ref="picker0" :data="picker0.data" :anchor="picker0.anchor" @confirm="handlePicker0Confirm" colorConfirm="#F60">
      </awesome-picker>
      <awesome-picker ref="picker1" :data="picker1.data" :anchor="picker1.anchor" @confirm="handlePicker1Confirm" colorConfirm="#F60">
      </awesome-picker>-->
    </div>
  </div>
</template>
<script>
  import {
    getReturnGoods,
    upload,
    applyReturnGoods,
    updateReturnGoods
  } from '@/api/order'
  import {
    mapGetters
  } from 'vuex'
  import lrz from 'lrz'
  import {
    Toast
  } from 'mint-ui'
  export default {
    data() {
      return {
        freight: '',
        returnTotalMoney: 0,
        stateVisible: false,
        reasonVisible: false,
        returnGoodsStatus: 1, // 当未发货售后状态
        stateSlots: [{
          defaultIndex: 0,
          flex: 1,
          values: [{
            id: 1,
            name: '没有收到商品'
          }, {
            id: 2,
            name: '已经收到商品'
          }],
          textAlign: 'center'
        }],
        reasonSlots: [{
          flex: 1,
          values: ['仓库缺货', '未按约定时间发货', '不想买了/订单下错了', '不想买了，已与客服协商', '大小/尺寸不符', '无理由退货', '颜色/图案/款式不符', '破损/污渍/划痕',
            '其他'
          ],
          textAlign: 'center'
        }],
        returnDetails: {
          returnGoodsStatus: '',
          returnReason: '请选择',
          returnNote: '',
          returnType: ''
        },
        returnGoods: {
          orderDiscountTotalMoney: 0,
          orderFreight: 0
        },
        flag: false,
        returnNum: '',
        returnImg: [],
        imgUrls: [],
        isPhoto: true,
        isAdd: true,
        fileArr: []
      }
    },
    watch: {
      imgUrls: 'toggleAddPic'
    },
    components: {},
    created() {
      this.fetchData()
    },
    computed: {
      ...mapGetters({
        userInfo: 'userInfo'
      }),
      freightPlaceholder() {
        return '不得超过¥' + this.$options.filters.formatMoney(this.returnGoods.orderFreight)
      }
    },
    methods: {
      handlestatePickerDataConfirm() { // 获取选择的货品情况
        this.returnDetails.returnGoodsStatus = this.$refs.statePickerDataPicker.getValues()[0].id
        this.stateVisible = false
      },
      handleReasonConfirm() { // 获取选择的退款原因
        this.returnDetails.returnReason = this.$refs.reasonPicker.getValues()[0]
        this.reasonVisible = false
      },
      fetchData() {
        // 获取数据
        // 判断是否登录
        if (!this.userInfo) return
        // 确认售后商品信息
        const formData = {
          userId: this.userInfo.id,
          orderId: this.$route.query.orderId,
          orderGoodsId: this.$route.query.orderGoodsId
        }
        if (this.$route.query.returnId) {
          formData.returnId = this.$route.query.returnId
        }
        getReturnGoods(formData).then(res => {
          // 售后详情
          this.returnGoods = res.data.returnGoods

          // 售后数量
          let numStr = this.$route.query.num.toString()

          // 只有一个商品的时候直接Number(numStr)
          numStr = numStr.indexOf(',') !== -1 ? numStr.split(',') : Number(numStr)

          // 售后总价
          let total = 0
          let returnNum = ''
          this.returnGoods.orderGoodsList.forEach((item, index) => {
            let goodNum = 0
            if (isNaN(Number(numStr))) {
              goodNum = Number(numStr[index]) > item.goodsNum ? item.goodsNum : Number(numStr[index])
            } else {
              // 只有一个商品的时候直接 numStr
              goodNum = Number(numStr) > item.goodsNum ? item.goodsNum : Number(numStr)
            }

            total += item.goodsDiscountPrice * goodNum
            returnNum += goodNum + ','
          })

          this.returnTotalMoney = total
          this.returnNum = returnNum

          if (res.data.returnDetails !== null) {
            // 修改的时候显示运费
            this.freight = this.returnGoods.orderFreight
            this.returnDetails = res.data.returnDetails
            // 设置初始值售后原因初始值
            this.$set(this.stateSlots[0], 'defaultIndex', this.returnDetails.returnGoodsStatus - 1)
            const index = this.reasonSlots[0].values.findIndex(item => item === this.returnDetails.returnReason)
            this.$set(this.reasonSlots[0], 'defaultIndex', index)
            this.returnDetails.returnImgList.forEach(item => {
              this.imgUrls.push(item.returnImg)
            })
            // 复制已经售后上传的图片
            this.returnImg = [...this.imgUrls]
          }
        })
      },
      toggleAddPic() {
        const vm = this
        if (vm.imgUrls.length >= 1) {
          vm.isPhoto = false
          if (vm.imgUrls.length >= 5) {
            vm.isAdd = false
          } else {
            vm.isAdd = true
          }
        } else {
          vm.isPhoto = true
        }
      },
      addPic(e) {
        const els = this.$refs.divGenres.querySelectorAll('input[type=file]')
        els[0].click()
        return false
      },
      onFileChange(e) {
        var files = e.target.files || e.dataTransfer.files
        if (!files.length) return
        this.createImage(files, e)
      },
      createImage(file, e) {
        const vm = this
        lrz(file[0], {
          width: 480
        }).then((rst) => {
          vm.imgUrls.push(rst.base64)
          vm.fileArr.push(rst.origin)
          return rst
        }).always(() => {
          // 清空文件上传控件的值
          e.target.value = null
        })
      },
      delImage(index) {
        this.imgUrls.splice(index, 1)
        // 删除回显照片
        this.returnImg.splice(index, 1)
      },
      previewImage(url) {
        const vm = this
        vm.isPreview = true
        vm.previewImg = url
      },
      applyReturnSubmit() {
        const updateParams = {
          'userId': this.userInfo.id,
          'orderId': this.$route.query.orderId,
          'returnType': this.returnDetails.returnGoodsStatus,
          'orderGoodsId': this.$route.query.orderGoodsId,
          'returnNum': this.returnNum,
          'returnGoodsStatus': this.returnDetails.returnGoodsStatus,
          'returnReason': encodeURI(this.returnDetails.returnReason),
          'returnPrice': this.returnGoods.orderDiscountTotalMoney,
          'returnFreight': Number(this.freight),
          'returnNote': encodeURI(this.returnDetails.returnNote),
          'returnImg': this.returnImg
        }
        // console.log(updateParams)

        if (this.$route.query.returnId) {
          updateParams.returnId = this.$route.query.returnId
          updateReturnGoods(updateParams).then(res => {
            this.$router.replace({
              name: 'order',
              query: {
                tab: this.returnGoods.orderStatus
              }
            })
          }).catch(err => {
            Toast(err.info)
          })
        } else {
          applyReturnGoods(updateParams).then(res => {
            this.$router.replace({
              name: 'order',
              query: {
                tab: this.returnGoods.orderStatus
              }
            })
          }).catch(err => {
            Toast(err.info)
          })
        }
      },
      submit() {
        if (this.returnDetails.returnGoodsStatus === '') return Toast('请选择货品情况')
        if (this.returnDetails.returnReason === '请选择') return Toast('请选择退货原因')
        if (this.freight === '') return Toast('运费不能为空，最小是0')
        if (isNaN(Number(this.freight))) return Toast('运费为数字')
        this.freight = Number(this.freight).toFixed(2)
        if (this.freight > this.returnGoods.orderFreight) return Toast('退款运费应小于总运费')
        if (this.returnDetails.returnNote === '') return Toast('请填写售后说明')

        // 如果有图片则上传
        this.returnImg = this.returnImg.length > 0 ? this.returnImg.join(',') : ''
        if (this.fileArr.length > 0) {
          // 上传图片
          const param = {
            'type': 'after'
          }
          const imgData = new FormData()
          for (var i = 0; i < this.fileArr.length; i++) {
            imgData.append('file', this.fileArr[i])
          }
          upload(imgData, param).then(res => {
            this.returnImg = res.data.url + ',' + this.returnImg
            // 提交或更新售后
            this.applyReturnSubmit()
          }).catch(err => {
            Toast(err.info)
          })
        } else {
          // 如果是退货退款要上传照片
          if (this.returnGoods.orderStatus > 2 && this.returnImg.length <= 0) return Toast('请上传照片')
          // 提交或更新售后
          this.applyReturnSubmit()
        }
      }
    },
    filters: {
      formatStatus(val) {
        return val === 1 ? '没有收到商品' : val === 2 ? '已经收到商品' : '请选择'
      }

    }
  }

</script>
<style lang="scss">
  @import '~assets/common/css/mixin.scss';
  .refund-pricker {
    width: 100%;
    .picker-header {
      @include flexbox(space-between,
      center,
      row,
      nowrap);
      background: #EBEBF5;
      span {
        padding: $padding;
        font-size: 14px;
        display: block;
        &.red {
          color: $red;
        }
      }
    }
    .address-container {
      padding-bottom: 100px;
    }
  }

  .refund-from {
    padding-top: 1.25rem;
    background: #fff;
    .cell-from-item {
      @include flexbox(space-between,
      center,
      row,
      nowrap);
      padding: $padding;
      border-bottom: 1px solid #eee;
      .title {
        font-size: $subtitle;
        color: #333;
        white-space: nowrap;
        margin-right: 10px;
      }
      .content {
        width: 100%;
        input {
          width: 100%;
          border: none;
          outline: none;
          box-shadow: none;
          text-shadow: none;
          text-align: right;
          font-size: $subtitle;
          color: #333;
          line-height: 24px;
          &.gray {
            color: $gray;
          }
        }
        .bgc {
          background-color: #F8F8F8;
          display: block;
          height: 35px;
          line-height: 35px;
          text-align: right;
          padding-right: 10px;
          margin-left: 10px;
          color: $gray;
        }
      }
      .icon-right {
        font-size: 16px;
        color: $gray;
      }
      &.switch {
        justify-content: space-between;
      }
    }

    .save-address {
      bottom: .2rem;
      width: 90%;
      text-align: center;
      padding: $padding 0;
      background: $red;
      font-size: $title;
      color: #fff;
      margin: .5rem auto;
      border-radius: 2px;
    }
    .del-address {
      bottom: .2rem;
      width: 90%;
      text-align: center;
      padding: $padding 0;
      background: #f3f3f3;
      font-size: $title;
      color: #000;
      margin: .5rem auto;
      border-radius: 2px;
    }
  }

  .fillRefundInfo {
    min-height: 100vh;
    padding-bottom: 45px;
    header {
      height: 45px;
      background-color: #FFF;
      color: #000;
      border-bottom: 1px solid #ECECEC;
      z-index: 2!important;
    }
    .submit {
      button {
        height: 45px;
        width: 100%;
        font-size: 14px;
        line-height: 45px;
        background-color: #F60;
        color: #FFF;
        text-align: center;
        position: fixed;
        bottom: 0;
      }
    }
    .refund-info {
      padding-left: 15px;
      background-color: #fff;
      p {
        height: 50px;
        line-height: 50px;
        padding-right: 15px;
        position: relative;
        border-bottom: 1px solid #D9E0E5;
        .right {
          float: right;
          input {
            margin-right: 20px;
            text-align: right;
          }
          .more-right::after {
            border: solid 2px #c8c8cd;
            border-bottom-width: 0;
            border-left-width: 0;
            content: " ";
            top: 50%;
            right: 20px;
            position: absolute;
            width: 5px;
            height: 5px;
            -webkit-transform: translateY(-50%) rotate(45deg);
            transform: translateY(-50%) rotate(45deg);
          }
        }
        .bgc {
          background-color: #F8F8F8;
          width: 80%;
          height: 35px;
          line-height: 35px;
          text-align: right;
          margin-top: 7.5px;
          padding-right: 10px;
        }
      }
      p:nth-last-child(1) {
        border-bottom: none;
      }
    }
    .explain {
      height: 100px;
      background-color: #fff;
      padding: 15px;
      margin: 10px 0;
      textarea {
        resize: none;
        width: 100%;
        height: 100%;
      }
    }
    .upload {
      // height: 150px;
      overflow: hidden;
      background-color: #fff;
      padding: 15px;
    }
    .list-ul {
      @include flexbox(flex-start,
      center,
      row,
      wrap); // list-style: none;
      // margin: 0px;
      // padding: 0px;
      // width: auto;
      // overflow: hidden;
    }
    .list-li {
      flex: 0 0 33%;
      padding: 5px;
      height: 110px;
      text-align: center;
      position: relative;
    } // .list-link {
    //   overflow: hidden; 
    //    height: 100px;
    //    width: 100px;
    //    display: table-cell;
    //     text-align: center;
    //     vertical-align: middle;
    // }
    .list-link img {
      max-width: 100%;
      max-height: 100px;
    } // .list-link a:visited {
    //   background-color: #465c71;
    //   /* 背景色 */
    //   border: 1px #4e667d solid;
    //   /* 边框 */
    //   color: #dde4ec;
    //   /* 文字颜色 */
    //   display: flex;
    //   /* 此元素将显示为块级元素，此元素前后会带有换行符 */
    //   line-height: 1.35em;
    //   /* 行高 */
    //   padding: 4px 20px;
    //   /* 内部填充的距离 */
    //   text-decoration: none;
    //   /* 不显示超链接下划线 */
    //   white-space: nowrap;
    //   /* 对于文本内的空白处，不会换行，文本会在在同一行上继续，直到遇到 <br> 标签为止。 */
    //   overflow: hidden;
    // }
    // /* 所有class为menu的div中的ul中的a样式(鼠标移动到元素中的样式) */
    // .list-link a:hover {
    //   background-color: #bfcbd6;
    //   /* 背景色 */
    //   color: #465c71;
    //   /* 文字颜色 */
    //   text-decoration: none;
    //   /* 不显示超链接下划线 */
    // }
    // /* 所有class为menu的div中的ul中的a样式(鼠标点击元素时的样式) */
    // .list-link a:active {
    //   background-color: #465c71;
    //   /* 背景色 */
    //   color: #cfdbe6;
    //   /* 文字颜色 */
    //   text-decoration: none;
    //   /* 不显示超链接下划线 */
    // }
    .list-img-close {
      background: #ffffff url('~assets/common/images/delete.svg') no-repeat right top;
      border-color: #ff4a00;
      background-position: center;
      background-size: 20px 20px;
      display: block;
      float: left;
      width: 20px;
      height: 20px;
      position: absolute;
      top: 0;
      left: 0;
      margin-top: 0px;
      margin-left: 0px;
      padding: 8px;
      z-index: 10;
      border-radius: 5px;
      text-align: center;
    }

    .add-img {
      display: block;
      background-image: url('~assets/common/images/add.svg');
      background-repeat: no-repeat;
      width: 100px;
      height: 100px;
      background-position: center;
      background-size: 100px 100px;
    }
  }

</style>
